"""
主应用入口
"""
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.routing import APIRouter
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
import os

from backend.app.utils.config import settings
from backend.app.router import auth, user, admin
from backend.app.db.database import engine, Base
from backend.app.utils.logger import logger

# 创建数据库表
Base.metadata.create_all(bind=engine)

# 创建FastAPI应用
app = FastAPI(
    title=settings.PROJECT_NAME
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.CORS_ORIGINS,  # 使用配置文件中的CORS设置
    allow_credentials=True,  # 允许携带凭证
    allow_methods=["*"],  # 允许的HTTP方法
    allow_headers=["*"],  # 允许的HTTP头
)

# 创建API路由
api_router = APIRouter()
# 注册路由
api_router.include_router(auth.router)
api_router.include_router(user.router)
api_router.include_router(admin.router)
# 将API路由添加到应用
app.include_router(api_router, prefix="/api")

# 挂载静态文件目录
app.mount("/static", StaticFiles(directory="static"), name="static")

@app.get("/")
async def root():
    """根路由，返回前端页面"""
    return FileResponse("static/index.html")

@app.get("/{path:path}")
async def serve_spa(path: str):
    """处理前端路由，返回index.html"""
    return FileResponse("static/index.html") 